package com.vert.c3p0;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Map;

/**
 * @Classname C3P0DataSource
 * @Description TODO
 * @Date 2022/5/27 11:56
 * @Created by XiongXiong
 * @Author: X.I.O
 */
public class C3P0DataSource {

      private static  ComboPooledDataSource ds;

      private String url;

      private String driver;

      private String password;

      private String username;


      public C3P0DataSource(Map<String,String> stringMap) {
            this.url = stringMap.get("url");
            this.driver = stringMap.get("driver");
            this.password = stringMap.get("password");
            this.username = stringMap.get("username");
            this.initConnection();
      }

    public C3P0DataSource(String url, String driver, String password, String username) {
          this.url = url;
          this.driver = driver;
          this.password = password;
          this.username = username;
          this.initConnection();
    }

  private void initConnection() {
        try {
          if(C3P0DataSource.ds==null){
            ds = new ComboPooledDataSource();
          }
          ds.setDriverClass(driver);
          ds.setJdbcUrl(url);
          ds.setUser(username);
          ds.setPassword(password);

          //当连接池中的连接耗尽的时候c3p0一次同时获取的连接数
          ds.setAcquireIncrement(3);
          //初始化数据库连接池时连接的数量
          ds.setInitialPoolSize(10);
          //数据库连接池中的最小的数据库连接数
          ds.setMinPoolSize(2);
          //数据库连接池中的最大的数据库连接数
          ds.setMaxPoolSize(10);
        } catch (PropertyVetoException var3) {
          var3.printStackTrace();
        }
      }

      public Connection getConnection() {
        Connection connection=null;
        try {
          if(ds==null){
            this.initConnection();
          }
          connection=ds.getConnection();
          return connection;
        }catch (SQLException var4) {
            var4.printStackTrace();
        }
        return null;
      }

      public void clonse(Connection connection){
          if(connection!=null){
            try {
              connection.close();
            }catch (SQLException var4) {
                var4.printStackTrace();
            }

          }
      }



}
